package com.phuc.app.vuivui;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.phuc.app.vuivui.sqlite.StoryDto;
import com.phuc.app.vuivui.sqlite.TBL_STORY_dao;
import com.phuc.app.vuivui.utils.Utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static com.phuc.app.vuivui.utils.Constants.*;

public class ReadingActivity extends FragmentActivity {

	// Read types
	public static final int READ_TYPE_ALL = 1;
	public static final int READ_TYPE_TEXT = 2;
	public static final int READ_TYPE_IMAGE = 3;
	public static final int READ_TYPE_LIKE = 4;
	
	/**
	 * List of all story id that not read by user.
	 */
	public static ArrayList<Integer> listId;
	
	/**
	 * Check if reading activity is load first time or not.
	 */
	public static boolean isLoadFirstTime;
	
	/**
	 * Type of reading.
	 */
	private int type;
	
	/**
	 * The adapter that content of story will show into.
	 */
	private ImageAdapter mAdapter;

	private ViewPager mPager;
	
	private AdView adView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			// Get selected theme
			int selecedTheme = getIntent().getExtras().getInt(MainMenuActivity.SHARE_PREFER_THEME_KEY);
			if (selecedTheme == 2) {
				setContentView(R.layout.reading_2);
			} else if (selecedTheme == 3) {
				setContentView(R.layout.reading_3);
			} else {
				setContentView(R.layout.reading);
			}
	
			// If is first time load, initialize list of story id
			if (isLoadFirstTime || listId  == null) {
				initData();
		        isLoadFirstTime = false;
			}
			
			mAdapter = new ImageAdapter(getSupportFragmentManager());
	        mPager = (ViewPager)findViewById(R.id.pager);
	        mPager.setAdapter(mAdapter);
	        mAdapter.notifyDataSetChanged();
			
	        adView = (AdView) findViewById(R.id.adView);
	        if (adView != null) {
	        	adView.loadAd(new AdRequest());
	        }
		} catch (Exception ex) {
			finish();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.read_menu2, menu);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem itm = menu.findItem(R.id.read_like);
		int selectedStoryId = listId.get(mPager.getCurrentItem());
		StoryDto story = TBL_STORY_dao.findById(selectedStoryId);
		if (story.isIslike()) {
			itm.setIcon(R.drawable.icon_star);
			itm.setTitle(R.string.menu_unlike);
		} else {
			itm.setIcon(R.drawable.icon_star_none);
			itm.setTitle(R.string.menu_like);
		}
		return super.onPrepareOptionsMenu(menu);
	}
	
	private void initData() {
		Bundle extras = this.getIntent().getExtras();
		type = extras.getInt(INTENT_PARAM_READ_TYPE);
		initListId();
	}
	
	private void initListId() {
		ArrayList<Integer> listTemp = null;
		
		switch (type) {
		case READ_TYPE_ALL:
			listTemp = TBL_STORY_dao.getAllIdByType(0);
			break;
		case READ_TYPE_TEXT:
			listTemp = TBL_STORY_dao.getAllIdByType(1);
			break;
		case READ_TYPE_IMAGE:
			listTemp = TBL_STORY_dao.getAllIdByType(2);
			break;
		case READ_TYPE_LIKE:
			listTemp = TBL_STORY_dao.getAllLikeId();
			break;
		default:
			break;
		}
		
		// Check if list size is zero, update all story to unread and re-find
		if (listTemp.size() == 0) {
			TBL_STORY_dao.updateAllToUnread(type);
			switch (type) {
			case READ_TYPE_ALL:
				listTemp = TBL_STORY_dao.getAllIdByType(0);
				break;
			case READ_TYPE_TEXT:
				listTemp = TBL_STORY_dao.getAllIdByType(1);
				break;
			case READ_TYPE_IMAGE:
				listTemp = TBL_STORY_dao.getAllIdByType(2);
				break;
			case READ_TYPE_LIKE:
				listTemp = TBL_STORY_dao.getAllLikeId();
				break;
			default:
				break;
			}
		}
		
		// Fill random id from listTemp to listId
		if (listId == null) {
			listId = new ArrayList<Integer>();
		}
		listId.clear();
		while (listTemp.size() > 0) {
			listId.add(listTemp.remove(Utils.makeRandomNumber(listTemp.size())));
		}
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.read_back:
			finish();
			break;
		case R.id.read_like:
			int selectedStoryId = listId.get(mPager.getCurrentItem());
			StoryDto story = TBL_STORY_dao.findById(selectedStoryId);
			story.setIslike(!story.isIslike());
			TBL_STORY_dao.update(story);
			break;
		case R.id.read_share:
			Intent intent_share_facebook = getIntentFacebook();
			finish();
			startActivity(intent_share_facebook);
		default:
			break;
		}
		return true;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	private Intent getIntentFacebook(){
		int selectedStoryId = listId.get(mPager.getCurrentItem());
		StoryDto story = TBL_STORY_dao.findById(selectedStoryId);

		Intent intent_facebook =null;
		intent_facebook = new Intent(Intent.ACTION_SEND);
		intent_facebook.setType("text/plain");
		intent_facebook.putExtra(Intent.EXTRA_SUBJECT, "Sharing URL");
		if(story.getType() == 1){
			Toast.makeText(this, R.string.text_is_copied, Toast.LENGTH_LONG).show();
			int sdk = android.os.Build.VERSION.SDK_INT;
			if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
			    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			    clipboard.setText(story.getContent());
			} else {
			    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
			    android.content.ClipData clip = android.content.ClipData.newPlainText("text label", story.getContent());
			    clipboard.setPrimaryClip(clip);
			}
			intent_facebook.putExtra(Intent.EXTRA_TEXT,"Abc"+story.getContent());
		}else{
			intent_facebook.putExtra(Intent.EXTRA_TEXT,"Abc"+story.getContent());
		}
		PackageManager pm = getPackageManager();
		List<ResolveInfo> riList = pm.queryIntentActivities(intent_facebook, 0);
		for (final ResolveInfo app : riList) {
		    if ((app.activityInfo.packageName).equals("com.facebook.katana")) {
		        final ActivityInfo activity = app.activityInfo;
		        final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
		        intent_facebook.setComponent(name);
		        break;
		   }
		}
		
		return intent_facebook;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (adView != null) {
	        adView.destroy();
	    }
		clearCacheFolder(this.getCacheDir(), 0);
		Utils.unbindDrawable(findViewById(R.id.root));
        System.gc();
	}
	
	/**
	 * Method clear cache folder.
	 * @param dir
	 * @param numDays
	 * @return
	 */
	static int clearCacheFolder(final File dir, final int numDays) {
	    int deletedFiles = 0;
	    if (dir!= null && dir.isDirectory()) {
	        try {
	            for (File child:dir.listFiles()) {

	                //first delete subdirectories recursively
	                if (child.isDirectory()) {
	                    deletedFiles += clearCacheFolder(child, numDays);
	                }

	                //then delete the files and subdirectories in this dir
	                //only empty directories can be deleted, so subdirs have been done first
	                if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
	                    if (child.delete()) {
	                        deletedFiles++;
	                    }
	                }
	            }
	        }
	        catch(Exception e) { }
	    }
	    return deletedFiles;
	}
}
